package com.situ.stmall.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.situ.stmall.service.OrderService;

/**
 * 管理调度器与作业之间的相互处理
 * @author bobzyh
 *
 */
@Component
public class QuartzManager {

	// 注入一个调度器
	@Autowired
	private Scheduler scheduler;
	
	@Autowired
	private OrderService orderService;
	
	/*
	 * 向调度器中添加一个作业任务
	 */
	public void addJob(String orderId) {
		
		CleanOrderJob.orderService = orderService;
		
		// 1. 创建一个JobDetail		
		// 建造者模式: 需要一个建造者的对象, 可以设置需要的值, 建造者根据设置的值创建需要的对象
		JobDetail jobDetail = JobBuilder
				.newJob(CleanOrderJob.class)
				.withIdentity(orderId, orderId)
				.usingJobData("orderId", orderId)
				.build();
		
		Date now = new Date();
		Date exeDate = new Date(now.getTime() + 30*60*1000);
		
		SimpleDateFormat sdf = new SimpleDateFormat("s m H * * ?");
		String cron = sdf.format(exeDate); 
		System.err.println(cron);
		
		// 2. 创建一个触发器
		Trigger trigger = TriggerBuilder
				.newTrigger()
				.withIdentity(orderId, orderId)
				.startNow()
				.withSchedule(CronScheduleBuilder.cronSchedule(cron))
				.endAt(new Date( exeDate.getTime() + 10*1000) )
				.build();
		
		// 3. 调度任务
		try {
			scheduler.scheduleJob(jobDetail, trigger);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
